<template>
  <l-layout class="l-tab-page" v-if="!lr_loadPage">
    <template #left>
      <l-panel style="padding-right: 0">
        <template #title>
          {{ $t("流程分类") }}
          <div class="tree-setting-btn">
            <el-tooltip effect="dark" :content="$t('分类管理')" placement="top">
              <el-button
                @click="handleSettingClick"
                type="text"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </div>
        </template>
        <el-tree
          class="learun-tree"
          ref="tree"
          node-key="id"
          :highlight-current="true"
          :data="dataItemTree_FlowSort"
          @node-click="handleNodeClick"
        >
          <span class="lr-tree-node" slot-scope="{ node }">
            <i class="el-icon-notebook-2"></i>
            {{ node.label }}
          </span>
        </el-tree>
      </l-panel>
    </template>
    <l-panel style="padding-left: 0">
      <template #toolLeft>
        <div class="l-panel--item">
          <el-input
            :placeholder="$t('请输入模版名称')"
            v-model="searchWord"
            size="mini"
          >
          </el-input>
        </div>
      </template>
      <template #toolRight>
        <l-tool-btns :hasAdd="false">
          <l-wordprint-btn
            ref="wordprintBtn"
            @click="handlePrints"
            :label="$t('批量打印')"
            btnType="primary"
          ></l-wordprint-btn>
        </l-tool-btns>
      </template>
      <div style="display: flex; height: 100%; width: 100%;">
        <l-table
          :loading="tableLoading"
          :columns="columns"
          :dataSource="schemeDataList"
          row-key="f_Id"
          @rowClick="handleRowClick"
          style="width: 500px;border-right:1px solid #d9d9d9;"
        >
        </l-table>

        <l-table
          :loading="tableLoading2"
          :columns="columns2"
          :dataSource="tableData2"
          row-key="f_Id"
          :isPage="true"
          :isMultiSelect="true"
          :pageTotal="tableTotal2"
          :tablePage.sync="tableCurrentPage2"
          @loadPageData="turnTablePage2"
          style="flex: 2"
          ref="mainTable"
        >
          <template v-slot:f_MakeTime="scope">
            {{ lr_dateFormat(scope.row.f_MakeTime) }}
          </template>
          <template v-slot:f_IsFinished="scope">
            <el-tag v-if="scope.row.isDelete == 3" size="mini" type="danger">{{
              $t("作废")
            }}</el-tag>
            <el-tag
              v-else-if="scope.row.f_IsFinished == 1"
              size="mini"
              type="warning"
              >{{ $t("结束") }}</el-tag
            >
            <el-tag v-else size="mini" type="success">{{
              $t("审批中")
            }}</el-tag>
          </template>
        </l-table>
      </div>
    </l-panel>


    <wf-look-form
      ref="form"
      type="look"
      :params="{ taskId: taskId }"
      :isLoadFormData="true"
      :title="title"
      :visible.sync="visible"
      @printDataLoaded="printDataLoaded"
      :wfIsPrints="isPrints"
    >
    </wf-look-form>
  </l-layout>
</template>

<script>
const api = window.$api.workflow.scheme;
const apiProcess = window.$api.workflow.process;
export default {
  components: {},
  data() {
    return {
      // 左侧树形
      classifysVisible: false,
      treeCategory: "",
      // 搜索
      searchWord: "",

      // 表格
      columns: [
        { label: "编号", prop: "f_Code", minWidth: "150" },
        { label: "名称", prop: "f_Name", minWidth: "150" },
      ],
      columns2: [
        { label: "任务", prop: "f_UnitName", minWidth: 100, align: "left" },
        { label: "标题", prop: "f_ProcessTitle", minWidth: 100, align: "left" },
        { label: "审核", prop: "f_OperationName", width: 100, align: "center" },
        { label: "状态", prop: "f_IsFinished", width: 72, align: "center" },
        {
          label: "提交人",
          prop: "f_ProcessUserId",
          width: 160,
          align: "left",
          dataType: "fullUser",
          isNotAutoWrap: true,
        },
        { label: "时间", prop: "f_MakeTime", width: 160, align: "left" },
      ],
      tableLoading: false,
      tableData: [],
      schemeAuth: {},
      schemeCode: "",
      nodeIds: [],

      tableLoading2: false,
      tableTotal2: 0,
      tablePageSize2: 50,
      tableCurrentPage2: 1,
      tableData2: [],

      taskId: "",
      title: "",
      visible: false,

      isPrints: false,
      printList: [],
      printLoading: null,
      printIndex: 0,
      printHtml: "",
    };
  },
  computed: {
    dataItemTree_FlowSort() {
      return this.lr_dataItemTree(this.lr_dataItem["FlowSort"]);
    },
    schemeDataList() {
      let res = this.tableData;
      if (!this.$validatenull(this.searchWord)) {
        res = this.tableData.filter(
          (t) => t.f_Name.indexOf(this.searchWord) != -1
        );
      }

      return res;
    },
  },
  mounted() {
    this.lr_loadDataItem("FlowSort");
    this.loadScheme();
  },
  methods: {
    async loadScheme() {
      this.tableLoading = true;
      let { schemeAuthList, schemeinfoList } =
        (await this.$awaitWraper(api.getPrintList())) || {};
      let schemeAuth = {};
      for (let auth of schemeAuthList) {
        schemeAuth[auth.f_SchemeInfoId] = schemeAuth[auth.f_SchemeInfoId] || [];
        let sets = auth.f_ObjName.split("|");
        if (schemeAuth[auth.f_SchemeInfoId].indexOf(sets[2]) == -1) {
          schemeAuth[auth.f_SchemeInfoId].push(sets[2]);
        }
      }

      this.tableData = schemeinfoList || [];
      this.schemeAuth = schemeAuth;

      this.tableLoading = false;
    },
    handleRowClick({ row }) {
      this.schemeCode = row.f_Code;
      this.nodeIds = this.schemeAuth[row.f_Id];
      this.$refs.mainTable.clearSelection();
      this.loadTablePage2();
    },

    // 子表格数据
    async loadTablePage2(isNotFirst) {
      if (!isNotFirst) {
        this.tableCurrentPage2 = 1;
      }
      this.tableLoading2 = true;
      let queryData = {
        unitId: String(this.nodeIds),
        code: this.schemeCode,
      };

      const pagination = {
        rows: this.tablePageSize,
        page: this.tableCurrentPage,
        sidx: "t2.F_CreateDate DESC",
      };

      let data = await this.$awaitWraper(
        apiProcess.getPrintPage(pagination, queryData)
      );
      if (data != null) {
        this.tableData2 = data.rows.map((t, index) => ({
          ...t,
          id: t.f_Id + index,
        }));
        this.tableTotal2 = data.records;
      } else {
        this.tableData2 = [];
      }
      this.tableLoading2 = false;
    },
    turnTablePage2({ rows }) {
      this.tablePageSize2 = rows;
      this.loadTablePage2(true);
    },
    hanleSearch2() {
      this.loadTablePage();
    },
    // 批量打印
    handlePrints() {
      if (this.printList.length > 0) {
        return;
      }

      const list = this.$refs.mainTable.getSelected();
      if (list.length == 0) {
        this.$message({
          type: "warning",
          message: this.$t("请选择打印数据!"),
        });
        return;
      }
      this.isPrints = true;
      this.printIndex = 0;
      this.printList = list;
      this.printLoading = this.$loading({
        target: "document.body",
        lock: true,
        text: `${this.$t("打印数据加载中")}(0/${this.printList.length})...`,
        spinner: "el-icon-loading",
      });
      this.taskId = this.printList[this.printIndex].f_Id;
      this.visible = true;

      console.log(list, "批量打印reset");
    },
    printDataLoaded(html) {
      if(this.printList.length>0){
        if (html) {
        if (this.printHtml == "") {
          this.printHtml = html;
        } else {
          const _bodyHtml = html.match(/<body>.*<\/body>/g);
          this.printHtml = this.printHtml.replace(
            "</body>",
            _bodyHtml[0].replace(
              "<body>",
              '<div style="page-break-after:always;"></div><div style="height:10mm;width:100%;"></div>'
            )
          );
        }
      }
      this.visible = false;
      this.printLoading.close();
      this.printIndex++;
      if (this.printIndex == this.printList.length) {
        this.$nextTick(() => {
          if (this.printHtml) {
            this.$refs.wordprintBtn.print(this.printHtml);
          }
          this.printLoading = null;
          this.printList = [];
          this.printIndex = 0;
          this.printHtml = "";
        });
      } else {
        this.$nextTick(() => {
          this.printLoading = this.$loading({
            target: "document.body",
            lock: true,
            text: `${this.$t("打印数据加载中")}(${this.printIndex}/${this.printList.length})...`,
            spinner: "el-icon-loading",
          });
          this.taskId = this.printList[this.printIndex].f_Id;
          this.visible = true;
        });
      }
      }
    },

    // 分类
    handleNodeClick(node) {
      this.treeCategory = node.value;
      this.tableCurrentPage = 1;
      this.loadTablePage();
      this.tableData2 = [];
    },
    handleSettingClick() {
      this.classifysVisible = true;
    },
  },
};
</script>
